package net.yxsoft.service;

import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.kit.ZipKit;
import net.yxsoft.resource.SqlRes;
import net.yxsoft.service.common.BaseService;
import rapid.core.Authuser;
import rapid.core.ContextStateEnum;
import rapid.core.TResult;
import rapid.util.FileKit;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2019/6/25.
 */
public class LifeService extends BaseService {
  public static final LifeService INSTANCE = new LifeService();
  
  /**
  * @MethodName: getLifeNodes
  * @Description:
  * @param: cond
   * @param: userid
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 15:56
  * @author wj
  */
  public List<Record> getLifeNodes(Kv cond, String userid) {
    List<Record> records = query(SqlRes.LIFE + "lifenode", Kv.by("cond", cond));

    Record preRecord = null;
    for(Record record : records) {
      String frmids = record.getStr("attrib_12");
      String frmnames = record.getStr("attrib_13");

      List<String> frmid = Arrays.asList(frmids.split(","));
      List<String> frmname = Arrays.asList(frmnames.split(","));
      List<Integer> frmnum = new ArrayList<>();
      List<String> frmcode = new ArrayList<>();

      for(int i = 0; i < frmid.size(); i++) {
        String fid = frmid.get(i);
        int frmqty = Db.findFirst("SELECT COUNT(1) frmqty FROM FN_FORM_DATA WHERE attrib_01 = ? ", fid).getNumber("frmqty").intValue();
        frmname.set(i, frmname.get(i));
        frmnum.add(i, frmqty);

        String code = Db.findFirst("SELECT code FROM FN_FORM WHERE id = ? ", fid).getStr("code");
        frmcode.add(i, code);
      }

      Record acc = Db.findFirst("SELECT COUNT(1) uploadqty, group_concat(CASE WHEN A.attrib_15 = '1' THEN C.codename ELSE '' END) fjlx \n" +
                                    "FROM S_LIFECYC_EXAMPLE_NODE_ACC A \n" +
                                    "LEFT JOIN ts_code C\n" +
                                    "ON A.attrib_01 = C.customid AND C.codetype='FJLX' AND C.leaf='2' \n" +
                                    "WHERE A.row_id = ? \n", record.getStr("conflict_id"));

      int filnum = Db.findFirst("SELECT COUNT(1) filnum \n" +
                                    "FROM S_LIFECYC_EXAMPLE_NODE_FIL \n" +
                                    "WHERE row_id = ?  \n", record.getStr("conflict_id")).getNumber("filnum").intValue();

      Record nst = Db.findFirst("SELECT COUNT(1) nsqty FROM S_LIFECYC_EXAMPLE_NODE_PER A \n" +

                                    "INNER JOIN TS_USER C \n" +
                                    "ON A.ATTRIB_01  = C.id \n" +
                                    "WHERE 1 = 1 \n" +
                                    "AND A.ROW_ID = ? \n" +
                                    "AND C.id = ? \n", record.getStr("conflict_id"), userid);

      record.set("frmids", frmid);
      record.set("frmnames", frmname);
      record.set("frmnums", frmnum);
      record.set("frmcodes", frmcode);
      record.set("uploadnum", acc.getNumber("uploadqty").intValue());
      record.set("fjlx", acc.getStr("fjlx"));
      record.set("filnum", filnum);

      String prenodeid = "";
      int preuploadnum = 0;
      int prefilnum = 0;
      if(null != preRecord) {
        prenodeid = preRecord.getStr("conflict_id");
        preuploadnum = preRecord.getNumber("uploadnum").intValue();
        prefilnum = preRecord.getNumber("filnum").intValue();
      }
      record.set("prenodeid", prenodeid);
      record.set("preuploadnum", preuploadnum);
      record.set("prefilnum", prefilnum);

      preRecord = record;

      if(records.indexOf(record) < records.size() - 1) {
        record.set("nextset", (nst.getNumber("nsqty").intValue() > 0) ? "1" : "0");
        record.set("nextnodeid", records.get(records.indexOf(record) + 1).getStr("conflict_id"));
      } else {
        record.set("nextset", "0");
        record.set("nextnodeid", "");
      }
    }

    return records;
  }

  /**
  * @MethodName: getLifeNodesToCoumnCN
  * @Description:
  * @param: cond
   * @param: userid
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 15:56
  * @author wj
  */
  public List<Record> getLifeNodesToCoumnCN(Kv cond, String userid) {
    List<Record> records = query(SqlRes.LIFE + "lifenodecn", Kv.by("cond", cond));

    Record preRecord = null;
    for(Record record : records) {
      String frmids = record.getStr("关联表单");
      String frmnames = record.getStr("表单名称");

      List<String> frmid = Arrays.asList(frmids.split(","));
      List<String> frmname = Arrays.asList(frmnames.split(","));
      List<Integer> frmnum = new ArrayList<>();
      List<String> frmcode = new ArrayList<>();

      for(int i = 0; i < frmid.size(); i++) {
        String fid = frmid.get(i);
        int frmqty = Db.findFirst("SELECT COUNT(1) frmqty FROM FN_FORM_DATA WHERE attrib_01 = ? ", fid).getNumber("frmqty").intValue();
        frmname.set(i, frmname.get(i));
        frmnum.add(i, frmqty);

        String code = Db.findFirst("SELECT code FROM FN_FORM WHERE id = ? ", fid).getStr("code");
        frmcode.add(i, code);
      }

      Record acc = Db.findFirst("SELECT COUNT(1) uploadqty, group_concat(CASE WHEN A.attrib_15 = '1' THEN C.codename ELSE '' END) fjlx \n" +
              "FROM S_LIFECYC_EXAMPLE_NODE_ACC A \n" +
              "LEFT JOIN ts_code C\n" +
              "ON A.attrib_01 = C.customid AND C.codetype='FJLX' AND C.leaf='2' \n" +
              "WHERE A.row_id = ? \n", record.getStr("conflict_id"));

      int filnum = Db.findFirst("SELECT COUNT(1) filnum \n" +
              "FROM S_LIFECYC_EXAMPLE_NODE_FIL \n" +
              "WHERE row_id = ?  \n", record.getStr("conflict_id")).getNumber("filnum").intValue();

      Record nst = Db.findFirst("SELECT COUNT(1) nsqty FROM S_LIFECYC_EXAMPLE_NODE_PER A \n" +

              "INNER JOIN TS_USER C \n" +
              "ON A.ATTRIB_01  = C.id \n" +
              "WHERE 1 = 1 \n" +
              "AND A.ROW_ID = ? \n" +
              "AND C.id = ? \n", record.getStr("conflict_id"), userid);

      record.set("该节点动态表单id集合", frmid);
      record.set("该节点动态表单名称集合", frmname);
      record.set("该节点动态表单数据记录数", frmnum);
      record.set("该节点动态表单编号集合", frmcode);
      record.set("节点需要上传的附件数", acc.getNumber("uploadqty").intValue());
      record.set("该节点需要上传的附件类型", acc.getStr("fjlx"));
      record.set("节点已经上传的附件数", filnum);

      String prenodeid = "";
      int preuploadnum = 0;
      int prefilnum = 0;
      if(null != preRecord) {
        prenodeid = preRecord.getStr("conflict_id");
        preuploadnum = preRecord.getNumber("节点需要上传的附件数").intValue();
        prefilnum = preRecord.getNumber("节点已经上传的附件数").intValue();
      }
      record.set("当前人员对应的节点ID", prenodeid);
      record.set("当前人员该节点需要上传的附件数", preuploadnum);
      record.set("当前人员该节点已经上传的附件数", prefilnum);

      preRecord = record;

      if(records.indexOf(record) < records.size() - 1) {
        record.set("该节点当前用户是否有权限", (nst.getNumber("nsqty").intValue() > 0) ? "1" : "0");
        record.set("该节点下一个节点ID", records.get(records.indexOf(record) + 1).getStr("conflict_id"));
      } else {
        record.set("该节点当前用户是否有权限", "0");
        record.set("该节点下一个节点ID", "");
      }
    }

    return records;
  }
    /**
    * @MethodName: saveFils
    * @Description:
    * @param: nodeid
     * @param: type
     * @param: paths
     * @param: loginUser
    * @return * @return rapid.core.TResult
    * @throws
    * @date 2023/8/31 15:56
    * @author wj
    */
  public TResult saveFils(String nodeid, String type, String paths, Authuser loginUser) {
    String[] pths = paths.split(",");
    List<Record> records = new ArrayList<>();

    String Logs = "";

    for(int i = 0; i < pths.length; i++) {
      Record record = new Record();
      String uuid = StrKit.getRandomUUID();

      record.set("conflict_id", uuid);
      record.set("ROW_ID", nodeid);
      record.set("ATTRIB_01", type);
      record.set("ATTRIB_02", pths[i].replace("/files/", ""));
      record.set("ATTRIB_12", pths[i]);

      records.add(record);

      Logs += "主键:" + uuid + ",外键:" + nodeid + ",附件类型:" + type + ",附件路径：" + pths[i] + ";";
    }

    int[] c = Db.batchSave("S_LIFECYC_EXAMPLE_NODE_FIL", records, records.size());

    if(c.length > 0) {

      result.setState(ContextStateEnum.SUCCESS);
      //日志
      log(loginUser.getId(), loginUser.getName(), "生命周期", "上传附件", loginUser.getIp(), Logs);
    } else {
      result.setState(ContextStateEnum.FAIL);
    }

    return result;
  }
    /**
    * @MethodName: deleteFils
    * @Description:
    * @param: filids
     * @param: loginUser
    * @return * @return rapid.core.TResult
    * @throws
    * @date 2023/8/31 15:56
    * @author wj
    */
  public TResult deleteFils(String filids, Authuser loginUser) {
    String[] ids = filids.split(",");
    List<String> sqls = new ArrayList<>();

    for(String id : ids) {
      String sql = String.format("DELETE FROM S_LIFECYC_EXAMPLE_NODE_FIL WHERE conflict_id = '%s' ", id);
      sqls.add(sql);
    }

    int[] i = Db.batch(sqls, sqls.size());

    if(i.length > 0) {
      result.setState(ContextStateEnum.SUCCESS);
      //日志
      log(loginUser.getId(), loginUser.getName(), "生命周期", "删除附件", loginUser.getIp(), filids);
    } else {
      result.setState(ContextStateEnum.FAIL);
    }

    return result;
  }
    /**
    * @MethodName: batchZip
    * @Description:
    * @param: id
     * @param: rootPath
    * @return * @return rapid.core.TResult
    * @throws
    * @date 2023/8/31 15:56
    * @author wj
    */
  public TResult batchZip(String id, String rootPath) {
    TResult result = new TResult();

    String sql = "SELECT C.ATTRIB_01, A.ATTRIB_02, A.ATTRIB_12 \n" +
        "FROM S_LIFECYC_EXAMPLE_NODE_FIL A\n" +
        "INNER JOIN S_LIFECYC_EXAMPLE_NODE B\n" +
        "ON A.ROW_ID = B.conflict_id\n" +
        "INNER JOIN S_LIFECYC_EXAMPLE C\n" +
        "ON B.ROW_ID = C.conflict_id\n" +
        String.format("WHERE C.conflict_id = '%s' ", id);

    List<Record> records = Db.find(sql);

    if(records.size() == 0) {
      result.setState(ContextStateEnum.FAIL);
      result.setMessage("未查询到可下载附件！");
      return result;
    }

    String fs = "files" + File.separator;
    String basePath = rootPath + fs;
    String fPath = basePath + "attachment";
    String zPath = basePath + "zip";

    ZipKit.deleteDirectory(fPath);
    ZipKit.deleteDirectory(zPath);
    File filPath = new File(fPath); //存放路径
    if(!filPath.exists()) {
      filPath.mkdirs();
    }

    File zipPath = new File(zPath); //压缩文件
    if(!zipPath.exists()) {
      zipPath.mkdirs();
    }

    for(Record record : records) {
      FileKit.copy(new File(basePath + record.getStr("ATTRIB_02")), fPath + File.separator + record.getStr("ATTRIB_02"));
    }

    String rp = records.get(0).getStr("ATTRIB_01") + "附件.zip";
    String zp = zPath + File.separator + rp;
    if(ZipKit.zip(zp, fPath)) {
      result.setState(ContextStateEnum.SUCCESS);
      result.setData(File.separator + fs + "zip" + File.separator + rp);
    } else {
      result.setState(ContextStateEnum.FAIL);
      result.setMessage("下载失败！");
    }

    return result;
  }
}
